import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:haitao_app/view/LinePaint.dart';
import 'config/config.dart';
import 'table/resp_result.dart';
import 'config/http_util.dart';
import 'package:haitao_app/InfoDetail.dart';


class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return HomeFul();
  }
  
}

class HomeFul extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HomeWidget();
  }
  
}

class HomeWidget extends State<HomeFul>{
  final GlobalKey<ScaffoldState> _globalKey=new GlobalKey();
  String apptitle="首页";
  Scaffold mainSc;
  bool drawerOpen=false;
  List<RstData> _listData;
  int pager=1;
  int divid_id=5685521;
  String lastType="";
  String connection="";
  ScrollController _controller=ScrollController();
  
  HomeWidget(){
    _controller.addListener((){
      var maxs=_controller.position.maxScrollExtent;
      var posion=_controller.position.pixels;
      if(posion==maxs) {
        print("*****************");
        pager++;
        if(_listData!=null && _listData.length>0){
          divid_id=_listData[_listData.length-1].id;
        }
        _getServerData("sinceid=$divid_id$connection");
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(apptitle,style: TextStyle(color: Colors.white),),
        leading: IconButton(
            icon: drawerOpen?Icon(Icons.arrow_back,color: Colors.white,):Icon(Icons.menu,color: Colors.white,),
            onPressed: (){_changeDrawer();}
            ),
        backgroundColor: Color.fromARGB(255, 0, 175, 0),
      ),
      body: _setBody(),
    );
  }

  Future<Null> _onRefresh() async{
    pager=1;
    if(_listData!=null && _listData.length>0){
      divid_id=_listData[0].id;
    }
    _getServerData("markid=$divid_id$connection");
    return null;
  }

  // ignore: slash_for_doc_comments
  /** 控制侧边栏开关 **/
  void _changeDrawer(){
    if(_globalKey.currentState.isDrawerOpen){
      _globalKey.currentState.openEndDrawer();
      setState(() {
        drawerOpen=false;
      });
    }else{
      _globalKey.currentState.openDrawer();
      setState(() {
        drawerOpen=true;
      });
    }
  }
  
  // ignore: slash_for_doc_comments
  /** 抽屉 **/
  Widget _getDrawer(){
    List<Map<String,String>> s=type;
    return Container(
      width: 200,
      child: ListView.builder(
          itemCount: s.length,
          itemBuilder: (content,index){
            return _drawerItem(s[index]);
          }
      ),
      color: Colors.white,
    );
  }
//  Widget _getDrawer(){
//    List<Map<String,String>> s=type;
//    return DrawerController(
//      child: ListView.builder(
//          itemCount: s.length,
//          itemBuilder: (content,index){
//            return _drawerItem(s[index]);
//          }
//      ),
//      drawerCallback: (bnm){
//        print(bnm);
//      },
//      alignment: DrawerAlignment.start,
//
//    );
//  }

  // ignore: slash_for_doc_comments
  /** 侧边栏列表 item **/
  Widget _drawerItem(Map<String,String> map){
    if(map["title"]=="=="){
      return  Container(
        height: 1,
        decoration: BoxDecoration(
          color: Colors.black54,
        ),
        child: LinePaint(),
      );
    }else{
      return GestureDetector(
        onTap: (){
          _onDrawerItemClick(map);
        },
        child: Container(
          padding: EdgeInsets.only(left: 10,top: 8,bottom: 8),
          child: Text(map["title"]),
        ),
      );
    }
  }

  // ignore: slash_for_doc_comments
  /** 侧边栏 列表点击事件 **/
  void _onDrawerItemClick(Map<String,String> map){
    print(map.toString());
    if(lastType!=map["type"]) {
      pager = 1;
      String t = "";
      if (map["type"] == "all") {
        connection = "";
      } else {
        t = "-" + map["title"];
        if (map["type"] == "hot") {
          connection = "&onlyhots=1";
        } else if (map["type"] == "mall") {
          connection = "&mall=${map["mall"]}";
        } else if (map["type"] == "cate") {
          connection = "&cate=${map["cate"]}";
        }
      }
      _getServerData("markid=$divid_id$connection");
      setState(() {
        apptitle = "首页" + t;
      });
    }
    _changeDrawer();
  }

  // ignore: slash_for_doc_comments
  /** 首页 ***/
  Widget _setBody(){
    mainSc=Scaffold(
      key: _globalKey,
      drawer:_getDrawer(),
      body: _index(),
    );
    return mainSc;
  }

  // ignore: slash_for_doc_comments
  /** 首页列表 ***/
  Widget _index(){
    Widget listview=ListView.builder(
      itemCount: _listData==null?0:_listData.length,
      itemBuilder: (content,index){
        return _indexItem(_listData[index]);
      },
      controller: _controller,
    );
    return RefreshIndicator(
      child: listview,
      onRefresh: _onRefresh,
    );
  }
  // ignore: slash_for_doc_comments
  /** 首页列表item ***/
  Widget _indexItem(RstData data){
    return SizedBox(
      height: 110,
      child: InkWell(
        child: Container(
          decoration: BoxDecoration(
//            borderRadius: BorderRadius.all(Radius.circular(10)),
            border: Border.all(color: Colors.black54,width: 1),
          ),
          padding: EdgeInsets.only(bottom: 5,top: 5),
          margin: EdgeInsets.all(5),
          child: Row(
            children: <Widget>[
              _indexItemLeft(data.image),
              _indexItemRight(data),
            ],
          ),
        ),
        onTap: (){
          Navigator.of(context)
              .push(
              MaterialPageRoute(
                  builder: (cx)=>InfoDetail(id:data.id,title: data.title,)));
        },
      ),
    );
  }
  // ignore: slash_for_doc_comments
  /** item左侧 ***/
  Widget _indexItemLeft(String path){
    return Container(
      width: 100,
      height: 100,
      child: Image.network(path),
    );
  }
  // ignore: slash_for_doc_comments
  /** item右侧 ***/
  Widget _indexItemRight(RstData data){
    return Expanded(
      child: Column(
        children: <Widget>[
          _rightTop(data.title),
          _rightFoot(data.mall, data.fromsite, data.pubtime)
        ],
      ),
    );
  }
// ignore: slash_for_doc_comments
  /** item右侧  上部分***/
  Widget _rightTop(String title){
    return Container(
      alignment: Alignment.topLeft,
      child: Text(title),
    );
  }
// ignore: slash_for_doc_comments
  /** item右侧  下部分***/
  Widget _rightFoot(String mall,String from,String time){
    return Expanded(
      child: Container(
        alignment: Alignment.bottomLeft,
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.bottomLeft,
                child: Text(mall,style: TextStyle(color: Color.fromARGB(255, 0, 175, 0),fontSize: 10),),
              ),
            ),
            Expanded(
              flex: 2,
              child: Container(
                margin: EdgeInsets.only(right: 3),
                alignment: Alignment.bottomRight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text("$from·",style: TextStyle(color: Colors.grey,fontSize: 10),),
                    Text(time,style: TextStyle(color: Color.fromARGB(255, 0, 175, 0),fontSize: 10),),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getServerData("markid=$divid_id$connection");
  }

  void _getServerData(String urlConnection){
    HttpUtil().get("/getlist.php?$urlConnection",options: HttpUtil().options)
        .then((resp){
      RespResult result=RespResult.fromJson(resp.data);
      print(result.toString());
      var data=_listData;
      if(data==null){
        data=result.data;
      }else{
        if(pager==1){
          data.clear();
        }
        data.addAll(result.data);
      }
      setState(() {
        _listData=data;
      });
    });
  }
  
}